<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="投入度管理" data-page-identification="y_auhlddz3b2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_i5vpkrwxor 自定义模板_91za6gac5d -->
            <!--          新建人员-->
            <a-modal
                :visible="state.modalVisble"
                title="新建项目"
                centered
                @ok="handleSubmitPeople"
                @cancel="cancelSubmitPeople"
                :mask-closable="false"
                :keyboard="false"
                destroy-on-close
                :body-style="{
                    maxHeight: '800px',
                    overflowY: 'auto'
                }"
                :ok-button-props="{ loading: state.addLoading }"
            >
                <div class="form-div">
                    <a-form :model="state.modelForm" ref="modelRef">
                        <a-row :gutter="24">
                            <a-col :span="22">
                                <a-form-item
                                    label="项目"
                                    name="projectName"
                                    :rules="[{ required: true, message: '请选择项目', trigger: ['blur', 'change'] }]"
                                >
                                    <a-tree-select
                                        :disabled="projectDisabled"
                                        v-model:value="state.modelForm.projectName"
                                        show-search
                                        style="width: 100%"
                                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                        placeholder="请选择"
                                        allow-clear
                                        tree-default-expand-all
                                        :field-names="{
                                            children: 'children',
                                            label: 'projectName',
                                            value: 'projectName'
                                        }"
                                        :tree-data="state.treeData"
                                        tree-node-filter-prop="label"
                                        @change="handleProjectChange"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="22">
                                <a-form-item
                                    label="团队负责人"
                                    name="leaderList"
                                    :rules="[
                                        { required: true, message: '请选择团队负责人', trigger: ['blur', 'change'] }
                                    ]"
                                >
                                    <a-select
                                        :disabled="projectDisabled"
                                        placeholder="请选择"
                                        :options="peopleList"
                                        :allowClear="true"
                                        :showSearch="true"
                                        mode="multiple"
                                        :filterOption="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        :showArrow="true"
                                        v-model:value="state.modelForm.leaderList"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row v-for="(item, index) in state.modelForm.userInvestmentList" :key="index" :gutter="12">
                            <a-col :span="24" v-if="index == 0">
                                <a-divider style="background-color: #3875ff; margin-top: 0; margin-bottom: 16px" />
                            </a-col>
                            <a-col :span="22">
                                <a-form-item
                                    label="团队成员"
                                    :name="['userInvestmentList', index, 'userName']"
                                    :rules="[
                                        { required: true, message: '请输入人员名称', trigger: ['blur', 'change'] }
                                    ]"
                                >
                                    <a-select
                                        placeholder="请选择"
                                        :options="peopleList"
                                        :allowClear="true"
                                        :showSearch="true"
                                        :filterOption="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        :max-tag-count="1"
                                        :showArrow="true"
                                        v-model:value="state.modelForm.userInvestmentList[index].userName"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="2">
                                <MinusCircleOutlined
                                    style="cursor: pointer"
                                    title-="删除"
                                    @click="handleDeletePeopleItem(index)"
                                />
                            </a-col>
                            <a-col :span="22">
                                <a-form-item label="投入度(1=1人月)">
                                    <a-input-number
                                        style="width: 100%"
                                        v-model:value="state.modelForm.userInvestmentList[index].investment"
                                        min="0"
                                        max="1"
                                        placeholder="请输入"
                                        :precision="1"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="22">
                                <a-form-item label="贡献度(1=1%)">
                                    <a-input-number
                                        style="width: 100%"
                                        v-model:value="state.modelForm.userInvestmentList[index].contribution"
                                        min="0"
                                        max="100"
                                        :precision="0"
                                        placeholder="请输入"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-divider style="background-color: #3875ff; margin-top: 0; margin-bottom: 16px" />
                            </a-col>
                        </a-row>
                        <a-button type="primary" size="small" @click="handleAddPeopleItem">新增</a-button>
                        <!--                        <PlusCircleOutlined style="cursor: pointer" title-="新增" @click="handleAddPeopleItem" />-->
                    </a-form>
                </div>
            </a-modal>
            <!--          新建人员-->
            <div class="body">
                <div class="top-time">{{ state.dateStr }}</div>
                <div class="top-search">
                    <a-row :gutter="24" style="height: 32px">
                        <a-col :span="6" style="height: 32px">
                            <a-form-item label="月份筛选">
                                <a-date-picker
                                    v-model:value="state.filter.month"
                                    picker="month"
                                    value-format="YYYY-MM"
                                    style="width: 100%"
                                    :allowClear="false"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6" style="height: 32px">
                            <a-form-item label="团队负责人">
                                <a-select
                                    v-model:value="state.filter.teamLeader"
                                    :options="state.teamLeaderList"
                                    placeholder="请选择"
                                    show-search
                                    :field-names="{ label: 'label', value: 'value' }"
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6" style="height: 32px">
                            <a-form-item label="团队成员">
                                <a-select
                                    v-model:value="state.filter.userName"
                                    :options="state.peopleList"
                                    placeholder="请选择"
                                    show-search
                                    :field-names="{ label: 'label', value: 'value' }"
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-space size="middle">
                                <a-button type="primary" @click="getData">查询</a-button>
                                <a-button type="primary" ghost @click="resetData">重置</a-button>
                            </a-space>
                        </a-col>
                    </a-row>
                </div>
                <div class="content-main">
                    <div class="top-check">
                        <a-radio-group v-model:value="state.radioValue" button-style="solid" @change="getData">
                            <a-radio-button value="项目">项目</a-radio-button>
                            <a-radio-button value="人员">人员</a-radio-button>
                        </a-radio-group>
                        <a-space>
                            <a-button
                                v-permission="'3000000890_vid_jxrs8z7ef5'"
                                type="primary"
                                :loading="state.editLoading"
                                @click="showOrHiddenEdit"
                                >{{ state.isEdit ? '完成' : '编辑' }}</a-button
                            >
                            <a-button
                                v-if="state.radioValue === '项目'"
                                v-permission="'3000000890_vid_qq5nsj3bzb'"
                                type="primary"
                                :disabled="state.isEdit"
                                @click="handleAddPeople"
                            >
                                新建
                            </a-button>
                        </a-space>
                    </div>
                    <a-table
                        :columns="state.radioValue === '项目' ? projectColumns : peopletColumns"
                        :data-source="state.dataSource"
                        :scroll="{ y: state.tableHeight }"
                        :loading="state.tableLoading"
                        bordered
                        :pagination="false"
                        class="trd-table-box"
                    >
                        <template #bodyCell="{ column, record, text, index }">
                            <template v-if="column.dataIndex === 'projectName'">
                                <div class="project-name-content">
                                    <div>{{ text }}</div>
                                    <PlusCircleOutlined
                                        style="color: #3875ff; cursor: pointer"
                                        title="新增项目人员"
                                        @click="tableAddPeople(record)"
                                    />
                                </div>
                            </template>
                            <template v-if="column.dataIndex === 'numIndex'">
                                {{ index + 1 }}
                            </template>
                            <!--                                      投入度-->
                            <template v-if="column.dataIndex === 'investment'">
                                <a-input-number
                                    style="width: 100%"
                                    v-model:value="record.investment"
                                    v-if="state.isEdit"
                                    :precision="1"
                                    min="0"
                                    max="1"
                                />
                            </template>
                            <!--                                      投入度-->
                            <!--                                      团队贡献度-->
                            <template v-if="column.dataIndex === 'projectContribution'">
                                <span style="color: #ff0000" v-if="record.projectContribution !== 100">
                                    {{ text }}
                                </span>
                                <span v-else>{{ text }}</span>
                            </template>
                            <!--                                      团队贡献度-->
                            <!--                                      团队成员-->
                            <template v-if="column.dataIndex === 'userName'">
                                <div style="margin: 0 auto; cursor: pointer" v-if="record.toBeAssigned !== 0">
                                    <span style="color: #ff0000"> {{ text }}</span>
                                    <a-tooltip>
                                        <template #title>待分配投入度:{{ record.toBeAssigned }}</template>
                                        <ExclamationCircleOutlined style="color: #ff0000; margin-left: 4px" />
                                    </a-tooltip>
                                </div>
                                <span v-else>{{ text }}</span>
                            </template>
                            <!--                                      团队成员-->
                            <!--                                      贡献度-->
                            <template v-if="column.dataIndex === 'contribution'">
                                <a-input-number
                                    v-model:value="record.contribution"
                                    v-if="state.isEdit"
                                    style="width: 100%"
                                    :precision="0"
                                    min="0"
                                    max="100"
                                    @change="onContributionChange(record)"
                                />
                            </template>
                            <template v-if="column.dataIndex === 'opration'">
                                <a-popconfirm
                                    title="确定删除?"
                                    ok-text="确定"
                                    cancel-text="取消"
                                    @confirm="confirmDelete(record.id)"
                                    @cancel="cancel"
                                >
                                    <a-button type="link" size="small">删除</a-button>
                                </a-popconfirm>
                            </template>
                            <!--                                      贡献度-->
                        </template>
                    </a-table>
                </div>
            </div>
            <!-- end vid_i5vpkrwxor 自定义模板_91za6gac5d -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'

    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'

    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        const lastMonth = dayjs().subtract(1, 'month').format('YYYY-MM')
        state.dateStr = lastMonth
        // 格式化时间为 yyyy-mm
        state.filter.month = lastMonth
        state.importDate = lastMonth
        getTreeData()
        getAllJfPeople()
        getData()
    })
    const headerOffset = ref(150)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 180 - headerOffset.value
    }
    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })
    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
    const state = reactive({
        filter: {
            month: undefined,
            userName: undefined,
            teamLeader: undefined
        },
        importDate: undefined,
        dateStr: undefined,
        fileVisible: false,
        fileList: [],
        dataSource: [],
        radioValue: '项目',
        visible: false,
        fileLoading: false,
        trdTotal: 1,
        treeData: [],
        peopleList: [],
        teamLeaderList: [],
        okLoading: false,
        isEdit: false,
        tableLoading: false,
        tableHeight: 600,
        modalVisble: false,
        addLoading: false,
        editLoading: false,
        modelForm: {
            projectName: undefined,
            leaderList: [],
            userInvestmentList: []
        }
    })

    watch(
        () => state.filter.month,
        () => {
            if (state.filter.month) {
                const formattedDate = dayjs(state.filter.month, 'YYYY-MM').format('YYYY年MM月')
                state.dateStr = formattedDate
            }
        },
        { deep: true }
    )
    const completeRef = ref(null)
    const isFirst = ref(true)
    function getData() {
        state.tableLoading = true

        get(
            `/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment?userName=${
                state.filter.userName || ''
            }&month=${state.filter.month}&type=${state.radioValue === '项目' ? 'PROJECT' : 'PERSON'}&leader=${
                state.filter.teamLeader || ''
            }`
        )
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                if (isFirst.value) {
                    state.peopleList = Array.from(new Set(data.data.map(item => item.userName))).map(userName => ({
                        label: userName,
                        value: userName
                    }))
                    let leaders = data.data.flatMap(item => item.leaderList || [])
                    leaders = [...new Set(leaders)]
                    state.teamLeaderList = leaders.map(item => {
                        return {
                            label: item,
                            value: item
                        }
                    })
                    isFirst.value = false
                }
                state.dataSource = groupData(data.data, state.radioValue === '项目' ? false : true)
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    function getTreeData() {
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/performance_investment/goal_management_project/${state.filter.month}`
        ).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.treeData = data.data
        })
    }
    function resetData() {
        state.filter.userName = undefined
        state.filter.teamLeader = undefined
        const lastMonth = dayjs().subtract(1, 'month').format('YYYY-MM')
        state.filter.month = lastMonth
        getData()
    }

    function showOrHiddenEdit() {
        state.editLoading = true
        get(`/solution-ppm/api/v2/built-in-system-ppm/parameter/judge_time_control/${state.filter.month}/TEAM_LEADER`)
            .then(data => {
                if (!data.data) {
                    message.info('请在评分起止时间内操作')
                    return
                } else {
                    if (!state.isEdit) {
                        state.isEdit = true
                    } else {
                        const payLoadData = state.dataSource.map(item => {
                            return {
                                ...item,
                                investment: item.investment || 0,
                                contribution: item.contribution || 0
                            }
                        })
                        put(
                            '/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment',
                            payLoadData
                        )
                            .then(data => {
                                if (data.code !== 200) {
                                    message.error(data.message)
                                    return
                                }
                                message.success(data.message)
                                state.isEdit = false
                                getData()
                            })
                            .finally(() => {
                                state.editLoading = false
                            })
                    }
                }
            })
            .finally(() => {
                state.editLoading = false
            })
    }
    function handleAddPeople() {
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/parameter/judge_time_control/${state.filter.month}/LEADER_RATING`
        ).then(data => {
            if (!data.data) {
                message.info('请在评分起止时间内操作')
                return
            }
            projectDisabled.value = false
            state.modalVisble = true
            state.modelForm.userInvestmentList.push({ ...peopleItem })
        })
    }
    const modelRef = ref(null)
    function handleSubmitPeople() {
        modelRef.value.validate().then(() => {
            state.addLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment', {
                ...state.modelForm,
                month: state.filter.month
            })
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)
                    cancelSubmitPeople()
                    isFirst.value = true
                    getData()
                })
                .finally(() => {
                    state.addLoading = false
                })
        })
    }
    function confirmDelete(id) {
        del(`/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            isFirst.value = true
            getData()
        })
    }
    function cancelSubmitPeople() {
        state.modalVisble = false
        state.modelForm = {
            projectName: undefined,
            userInvestmentList: [],
            leaderList: []
        }
        projectDisabled.value = false
    }
    const rules = computed(() => ({
        projectName: [{ required: true, message: '请选择项目', trigger: ['blur', 'change'] }],
        investment: [{ required: true, message: '请输入投入度', trigger: ['blur', 'change'] }],
        userName: [{ required: true, message: '请输入人员名称', trigger: ['blur', 'change'] }],
        contribution: [{ required: true, message: '请输入贡献度', trigger: ['blur', 'change'] }]
    }))
    const projectColumns = ref([
        {
            title: '项目名称',
            dataIndex: 'projectName',
            align: 'center',
            customCell: ({ userNameRowSpan, projectNameRowSpan }) => {
                return {
                    rowSpan: projectNameRowSpan
                }
            }
        },
        {
            title: '团队负责人',
            dataIndex: 'leader',
            align: 'center',
            customCell: ({ userNameRowSpan, projectNameRowSpan }) => {
                return {
                    rowSpan: projectNameRowSpan
                }
            }
        },
        {
            title: '团队贡献度',
            dataIndex: 'projectContribution',
            align: 'center',
            customCell: ({ userNameRowSpan, projectNameRowSpan }) => {
                return {
                    rowSpan: projectNameRowSpan
                }
            }
        },
        {
            title: '团队成员',
            dataIndex: 'userName',
            align: 'center'
        },
        {
            title: '投入度（1=1人月）',
            dataIndex: 'investment',
            align: 'center'
        },
        {
            title: '贡献度（1=1%）',
            dataIndex: 'contribution',
            align: 'center'
        },
        {
            title: '操作',
            dataIndex: 'opration',
            width: 80,
            align: 'center'
        }
    ])
    const peopletColumns = ref([
        {
            title: '团队成员',
            dataIndex: 'userName',
            align: 'center',
            customCell: ({ userNameRowSpan, projectNameRowSpan }) => {
                return {
                    rowSpan: userNameRowSpan
                }
            }
        },
        {
            title: '项目名称',
            align: 'center',
            dataIndex: 'projectName'
        },
        {
            title: '投入度',
            dataIndex: 'investment',
            align: 'center'
        },
        {
            title: '贡献度',
            dataIndex: 'contribution',
            align: 'center'
        },
        {
            title: '操作',
            dataIndex: 'opration',
            width: 80,
            align: 'center'
        }
    ])

    function groupData(data, isPeopleColumns = false) {
        let projectName = ''
        let userName = ''

        return data.map((item, index) => {
            // 处理 projectName 合并：仅在 projectColumns 中
            if (!isPeopleColumns && projectName !== item.projectName) {
                projectName = item.projectName
                let projectNameRowSpan = 0

                // 计算 projectName 合并的行数
                for (let i = index; i < data.length; i++) {
                    if (data[i].projectName === projectName) {
                        projectNameRowSpan++
                    } else {
                        break
                    }
                }
                item.projectNameRowSpan = projectNameRowSpan
            } else {
                item.projectNameRowSpan = 0
            }

            // 仅在 peopleColumns 时合并人员
            if (isPeopleColumns && userName !== item.userName) {
                userName = item.userName
                let userNameRowSpan = 0

                // 计算 userName 合并的行数
                for (let i = index; i < data.length; i++) {
                    if (data[i].userName === userName) {
                        userNameRowSpan++
                    } else {
                        break
                    }
                }
                item.userNameRowSpan = userNameRowSpan
            } else {
                item.userNameRowSpan = 0
            }

            return item
        })
    }
    const peopleList = ref([])
    function getAllJfPeople() {
        get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then(({ data }) => {
            peopleList.value = data.userDtoList.map(item => {
                return {
                    label: item.name,
                    value: item.name
                }
            })
        })
    }
    const peopleItem = {
        investment: undefined,
        userName: undefined,
        contribution: undefined
    }
    function handleAddPeopleItem() {
        state.modelForm.userInvestmentList.push({ ...peopleItem })
    }
    function handleDeletePeopleItem(index) {
        if (state.modelForm.userInvestmentList.length === 1) {
            message.info('请至少保留一条数据')
            return
        }
        state.modelForm.userInvestmentList.splice(index, 1)
    }
    const projectDisabled = ref(false)
    function tableAddPeople(record) {
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/parameter/judge_time_control/${state.filter.month}/LEADER_RATING`
        ).then(data => {
            if (!data.data) {
                message.info('请在评分起止时间内操作')
                return
            }
            projectDisabled.value = false
            state.modalVisble = true
            projectDisabled.value = true
            state.modelForm.projectName = record.projectName
            state.modelForm.leaderList = record.leaderList
            state.modelForm.userInvestmentList.push({ ...peopleItem })
        })
    }
    // 递归查找节点
    function findNodeByValue(data, value) {
        for (const item of data) {
            if (item.projectName === value) {
                return item
            }
            if (item.children && item.children.length > 0) {
                const found = findNodeByValue(item.children, value)
                if (found) return found
            }
        }
        return null
    }

    function handleProjectChange(value) {
        const node = findNodeByValue(state.treeData, value)
        console.log(node)
        state.modelForm.leaderList = node?.teamLeaderList || []
    }
    //     贡献度实时变化
    function onContributionChange(changedRecord) {
        const projectName = changedRecord.projectName
        const sameProjectRecords = state.dataSource.filter(item => item.projectName === projectName)
        const total = sameProjectRecords.reduce((sum, item) => sum + (Number(item.contribution) || 0), 0)

        sameProjectRecords.forEach(item => {
            item.projectContribution = total
        })

        // 可选提示
        if (total > 100) {
            message.warning(`${projectName} 的团队贡献度超过 100%，请检查`)
        }
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
        bacckground-color: #fff;
    }

    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }

    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }

    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }

    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }

    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }

    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }

    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }

    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }

    /*样式*/
    .body {
        background-color: #fff;
        height: 100%;
        padding: 24px;
        padding-bottom: 0;
        position: relative;
    }
    .top-time {
        font-size: 18px;
        color: #3875ff;
        font-weight: 600;
        margin-bottom: 12px;
    }
    .top-search {
        height: 32px;
        margin-bottom: 16px;
    }
    .item-title {
        height: 40px;
        background: rgba(56, 117, 255, 0.15);
        border-radius: 4px 4px 0 0;
        border-left: 4px solid #3875ff;
        display: flex;
        padding: 10px 14px 10px 14px;
        justify-content: space-between;
    }
    .item-content {
        position: relative;
        height: 180px;
        overflow-y: auto;
        background: #f5f8ff;
        padding: 8px 16px;
    }
    .no-data-image {
        width: 66px;
        height: 80px;
        background-image: url('http://10.40.0.33:9001/file-storage/482099304502618112-source.png');
        background-size: cover;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .no-date-tip {
        font-size: 14px;
        color: #595959;
        letter-spacing: 0;
        font-weight: 400;
        margin-top: 84px;
    }
    .content-item {
        align-items: center;
        height: 33px;
        display: flex;
        justify-content: space-between;
    }
    .nut {
        height: 8px;
        width: 8px;
        background-color: #3875ff;
        border-radius: 50%;
    }
    .content-left {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 400;
    }
    .content-right {
        display: flex;
    }
    .normal-font {
        font-size: 14px;
        color: #595959;
        letter-spacing: 0;
        font-weight: 400;
    }
    .weight-font {
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
    }
    .modal-title {
        line-height: 20px;
        padding: 10px 24px;
        height: 40px;
        background: rgba(56, 117, 255, 0.1);
        border-radius: 4px;
        margin-bottom: 16px;
    }
    .modal-num {
        font-size: 16px;
        color: #3875ff;
        letter-spacing: 0;
        text-align: right;
        font-weight: 500;
    }
    .form-content {
        display: inline-block;
        width: calc(100% - 30px);
    }
    .module-item {
        position: relative;
    }
    .del {
        width: 28px;
        color: #3875ff;
        position: absolute;
        right: -10px;
        top: 5px;
    }
    .content-main {
        overflow-y: auto;
        overflow-x: hidden;
        background-color: #fff;
    }
    .empty-box {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .people-name {
        font-size: 16px;
        line-height: 20px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
    }
    .top-check {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
    }
    .trd-table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
    .form-div :deep(.ant3-form-item-label) {
        width: 130px;
    }
    .project-name-content {
        display: flex;
        gap: 8px;
        justify-content: center;
        align-items: center;
    }
    /*样式*/
</style>
